package com.cloud.point.concurrent.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import lombok.extern.slf4j.Slf4j;

/**
 * CyclicBarrier的使用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-22 17:19
 */
@Slf4j
public class TestCyclicBarrier {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // 计数最好与线程池保持一致
        CyclicBarrier barrier = new CyclicBarrier(2,
                //每次计数清0会执行
                () -> {
                    log.info("执行end");
                }
        );
        for (int i = 0; i < 3; i++) {
            pool.submit(() -> {
                log.info("{}running", Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
            pool.submit(() -> {
                log.info("{}running", Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        pool.shutdown();
    }

}
